﻿#include "conf.h"
#include "clog.h"
Conf* Conf::m_pConf;
Conf* Conf::getInstance()
{
    if(m_pConf == nullptr)
        m_pConf = new Conf();
    return m_pConf;
}

void Conf::init()
{
    FILE* fp = nullptr;
    fp = fopen("conf.json","rb");
    if(fp == nullptr)
    {
        CLog::getInstance()->writeLog("[Conf::init]=>open file fail!\n");
        qDebug()<<"[Conf::init]=>open file fail!\n";
        return;
    }
    fseek(fp,0,SEEK_END);
    int len = ftell(fp);
    fseek(fp,0,SEEK_SET);
    char* buff = new char[len+1];
    fread(buff,len,1,fp);
    buff[len] = 0;
    Json::Reader reader;
    Json::Value root;
    if(reader.parse(buff,root))
    {
        std::string str = "[Conf::init]=>SerIP:" + root["SerIP"].asString() + "\t" + "ChatPort:" + root["ChatPort"].asString() +  "\t" + "FilePort:" + root["FilePort"].asString() + "\t" + "ImgPort:" + root["ImgPort"].asString() + "\t" + "AudioPort:" + root["AudioPort"].asString() + "\t" + "VideoPort:" + root["VideoPort"].asString() + "\n";
        CLog::getInstance()->writeLog(str);
        m_ip = root["SerIP"].asCString();
        m_chatPort = root["ChatPort"].asUInt();
        m_filePort = root["FilePort"].asUInt();
        m_imgPort = root["ImgPort"].asUInt();
        m_audioPort = root["AudioPort"].asUInt();
        m_videoPort = root["VideoPort"].asUInt();
    }
    if(fp!=nullptr)
        fclose(fp);
}

void Conf::saveConf()
{
    QFile file("conf.json");
    if(!file.open(QIODevice::WriteOnly))
    {
        CLog::getInstance()->writeLog("[Conf::SaveConf]=>open file fail\n");
        qDebug() << "[Conf::SaveConf]=>open file fail\n";
        return;
    }
    Json::Value root;
    root["SerIP"] = m_ip.toStdString();
    root["ChatPort"] = m_chatPort;
    root["FilePort"] =  m_filePort;
    root["ImgPort"] = m_imgPort;
    root["AudioPort"] = m_audioPort;
    root["VideoPort"] = m_videoPort;
    file.write(root.toStyledString().c_str());
    file.flush();
    file.close();
}
